package cn.iocoder.yudao.module.cms.feedback.service;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cms.feedback.dal.dataobject.FeedbackDO;
import cn.iocoder.yudao.module.cms.feedback.dal.mysql.FeedbackMapper;
import cn.iocoder.yudao.module.cms.feedback.vo.AdminFeedbackPageReqVO;
import cn.iocoder.yudao.module.cms.feedback.vo.AppFeedbackCreateReqVO;
import cn.iocoder.yudao.module.cms.feedback.vo.FeedbackPageReqVO;
import cn.iocoder.yudao.module.cms.feedback.vo.FeedbackReplyReqVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.FORBIDDEN;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.cms.ErrorCodeConstants.FEEDBACK_INFO_NOT_EXISTS;

/**
 * 意见反馈信息 Service 实现类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Service
@Validated
public class FeedbackServiceImpl implements FeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Override
    public Long createFeedbackInfo(Long userId, AppFeedbackCreateReqVO createReqVO) {
        // 插入
        FeedbackDO infoDO = BeanUtils.toBean(createReqVO, FeedbackDO.class);
        infoDO.setUserId(userId);
        feedbackMapper.insert(infoDO);
        // 返回
        return infoDO.getId();
    }

    @Override
    public void replyFeedbackInfo(FeedbackReplyReqVO updateReqVO) {
        // 校验存在
        FeedbackDO feedbackDO = validateFeedbackExists(updateReqVO.getId());
        // 更新
        feedbackDO.setReply(updateReqVO.getReply());
        feedbackDO.setStatus(updateReqVO.getStatus());
        feedbackMapper.updateById(feedbackDO);
    }

    @Override
    public void deleteFeedbackInfo(Long userId, Long id) {
        // 校验存在
        FeedbackDO feedbackDO = validateFeedbackExists(id);
        if (!Objects.equals(userId, feedbackDO.getUserId())) {
            throw exception(FORBIDDEN);
        }
        // 删除
        feedbackMapper.deleteById(id);
    }

    private FeedbackDO validateFeedbackExists(Long id) {
        FeedbackDO feedbackDO = feedbackMapper.selectById(id);
        if (feedbackDO == null) {
            throw exception(FEEDBACK_INFO_NOT_EXISTS);
        }
        return feedbackDO;
    }

    @Override
    public FeedbackDO getFeedbackInfo(Long id) {
        return feedbackMapper.selectById(id);
    }

    @Override
    public PageResult<FeedbackDO> getFeedbackInfoPage(AdminFeedbackPageReqVO pageReqVO) {
        return feedbackMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<FeedbackDO> getFeedbackInfoPage(Long userId, FeedbackPageReqVO pageReqVO) {
        return feedbackMapper.selectPage(userId, pageReqVO);
    }
}
